package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.UserPoMapper;
import com.woniu.outlet.po.UserPo;
import com.woniu.outlet.rabbitmq.MessageRepo;
import com.woniu.outlet.redis.RedisUserRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class UserAdapter {

    @Autowired
    private UserPoMapper userPoMapper;

    @Autowired
    private RedisUserRepo redisUserRepo;

    @Autowired
    private MessageRepo messageRepo;


    public List<UserPo> findUsers() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisUserRepo.findUsers("user:list");
        List<UserPo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List>() {
            });
            return lists;
        }
        lists = userPoMapper.selectByExample(null);
        //存到redis
        redisUserRepo.saveUser("user:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public UserPo getUserById(Integer id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisUserRepo.findUsers("user:" + id);
        UserPo userPo = null;
        if (!StringUtils.isEmpty(str)) {
            userPo = mapper.readValue(str, new TypeReference<UserPo>() {
            });
            return userPo;
        }
        userPo = userPoMapper.selectByPrimaryKey(id);
        //存到redis
        redisUserRepo.saveUser("user:"+id,mapper.writeValueAsString(userPo));
        return userPo;
    }

    public void addUser(UserPo userPo){
        userPoMapper.insert(userPo);
        redisUserRepo.deleteUser("user:list");
        log.info("发送邮箱消息到rabbitmq=======================");
        messageRepo.sendMessage(userPo.getEmail());

    }

    public void updateUser(UserPo userPo){
        userPoMapper.updateByPrimaryKeySelective(userPo);
        redisUserRepo.deleteUser("user:list");
    }

    public void deleteUserById(Integer id){
        userPoMapper.deleteByPrimaryKey(id);
        redisUserRepo.deleteUser("user:list");
    }
}
